#include <iostream>
#include <pthread.h>
#include <mutex>

using namespace std;

class SingleInstance
{
public:
    static SingleInstance* getInstance();

    static void deleteInstance();

    void print();
private:
    SingleInstance();
    ~SingleInstance();
    SingleInstance(const SingleInstance& sig);
    const SingleInstance& operator=(const SingleInstance& sig);
private:
    static SingleInstance *m_instance;
    static mutex m_mutex;
};
mutex SingleInstance::m_mutex;
SingleInstance* SingleInstance::m_instance = NULL;
SingleInstance *SingleInstance::getInstance()
{

    if(m_instance == NULL)
    {
        unique_lock<mutex> lock(m_mutex);
        if(m_instance == NULL)
        {
            m_instance = new(std::nothrow) SingleInstance;
        }

    }
    return m_instance;
}
void SingleInstance::deleteInstance()
{
    unique_lock<mutex> lock(m_mutex);
    if(m_instance)
    {
        delete m_instance;
        m_instance = NULL;
    }
}
void SingleInstance::print()
{
    cout << "the instance address is :" << m_instance << endl;
}
SingleInstance::SingleInstance()
{
    cout << "new instance" << endl;
}
SingleInstance::~SingleInstance()
{
    cout << "unstruct instance" << endl;
}

void* PrintHello(void* threadid)
{
    pthread_detach(pthread_self());

    int tid = *((int *)threadid);
    cout << "this is thread ID:" << tid << endl;

    SingleInstance::getInstance()->print();
    pthread_exit(NULL);
}


int main(int argc,char* argv[])
{
    pthread_t threads[5] = {0};
    int index[5] = {0};

    int ret = 0;
    int i =0;
    for( i = 0;i<5;i++)
    {
        cout << "main creat thread " << i << endl;
        index[i] = i;
        ret = pthread_create(&threads[i],NULL,PrintHello,(void*)&(index[i]));
        if(ret)
        {
            cout << "error thread" << ret << endl;
            exit(-1);
        }
    }

    SingleInstance::deleteInstance();




    //cout << "hello" << endl;
    return 0;
}
